<template>
  <el-dialog
    :visible.sync="ruleVisible"
    :before-close="handleClose"
    :append-to-body="true"
    :lock-scroll="true"
    :class="{'global-mobile-dialog': showMobilePage}"
    class="rule-dialog medium-common-dialog-size"
    @open="open">
    <Title :title="ruleId ? '编辑规则' : '新建规则'" style="flex: 1;"/>
    <el-form label-width="auto" class="filter-form">
      <el-form-item label="规则计算公式">
        <el-tooltip v-if="formulaList && formulaList.length" popper-class="rule-tooltip-formula" placement="top" effect="light">
          <div slot="content" class="tooltip-formula-content">
            <span
              v-for="(tag, index) in formulaList"
              :key="index"
              class="formula-option-tag"
              @click.stop="deleteFormula(index)" > {{ tag.label }} </span>
          </div>
          <div class="formula-option">
            <div
              v-for="(tag, index) in formulaList"
              :key="index"
              class="formula-option-tag"
              @click.stop="deleteFormula(index)">{{ tag.label }}</div>
          </div>
        </el-tooltip>
        <div v-else class="formula-option">
          <div
            v-for="(tag, index) in formulaList"
            :key="index"
            class="formula-option-tag"
            @click.stop="deleteFormula(index)">{{ tag.label }}</div>
        </div>
      </el-form-item>
      <div class="title" style="margin-top: 20px">公式引用</div>
      <el-form-item label="字段">
        <el-cascader
          v-model="cascaderValue"
          :options="fieldList"
          placeholder="选择字段"
          class="filterableSelect"
          size="small"
          filterable
          clearable
          style="width: 240px"
          @change="filedSelect" />
        <el-button type="primary" size="small" class="quote-btn" @click="quoteFun(quoteField, 'cascaderValue')">引用</el-button>
      </el-form-item>
      <el-form-item label="数值">
        <!-- @mousewheel.native.prevent -->
        <el-input v-model="quoteValue" placeholder="请输入数字，可输入小数点" type="text" size="small" style="width: 240px" @input="keyupEvent" />
        <el-button type="primary" size="small" class="quote-btn" @click="quoteFun({label: quoteValue, value: Number(quoteValue)}, 'quoteValue')">引用</el-button>
      </el-form-item>
      <el-form-item label="计算元素">
        <div style="display:flex;padding-top:3px">
          <div
            v-for="(item, index) in mathTag"
            :key="index"
            class="quote-tag"
            @click="quoteFun(item)">{{ item.label }}</div>
        </div>
      </el-form-item>
      <el-form-item label="条件">
        <dataFilter ref="dataFilter" :close-dialog="closeDialog" @filterGroup="filterGroup"/>
      </el-form-item>
      <el-form-item>
        <el-button class="search-btn-style" plain type="primary" size="small" @click="toSumbit">提交</el-button>
        <el-button type="info" class="back-btn" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { ruleField, ruleAdd, ruleEdit, ruleInfo } from '@/api/supplier';
import dataFilter from './dataFilter';
import Title from '@/components/Title';
import { numerical } from '@/utils/numFormat';
import { mapState } from 'vuex';
export default {
  components: { dataFilter, Title },
  props: {
    ruleVisible: {
      type: Boolean,
      default: false
    },
    resourceGroupId: { // 资源组id
      type: Number,
      default: null
    },
    ruleId: { // 规则ID
      type: Number,
      default: null
    }
  },
  data() {
    return {
      closeDialog: false,
      cascaderValue: [],
      fieldList: [],
      conditionList: [],
      quoteField: {},
      formulaList: [],
      quoteValue: '',
      mathTag: [
        { label: '×', value: -1 },
        { label: '÷', value: -1 },
        { label: '+', value: -1 },
        { label: '-', value: -1 },
        { label: '(', value: -1 },
        { label: ')', value: -1 }
        // { label: 'avg', value: -1 },
        // { label: '∑', value: -1 },
        // { label: '△', value: -1 } // 总数
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    getInfo() {
      ruleInfo(this.ruleId).then(res => {
        const data = res.data;
        this.formulaList = data.formulaList ? data.formulaList : [];
        this.conditionList = data.conditionArr ? data.conditionArr : [];
        if (data.conditionArr && data.conditionArr.length) {
          data.conditionArr.map(item => {
            if (item.conditions.key === '下单形式') {
              item.conditions.value = JSON.parse(item.conditions.value);
            }
            return item;
          });
          this.$refs.dataFilter.filterList = data.conditionArr;
        } else {
          this.$refs.dataFilter.filterList = [{
            logic: 'or', // or,and
            conditions: {
              key: '', // 条件一
              value: '', // 条件二
              unit: '' // 操作，=,>,<,>=,<=
            }
          }];
        }
      });
    },
    handleClose() {
      this.$emit('ruleClose', false);
      this.closeDialog = !this.closeDialog; // 标记弹窗的关闭打开
    },
    open() { // 弹窗打开之后的调用
      this.getRuleField();
      if (this.ruleId) {
        this.getInfo();
      } else { // 如果是新建规则，打开弹窗后清空弹窗内容
        this.closeDialog = !this.closeDialog; // 标记弹窗的关闭打开
        this.formulaList = [];
        this.cascaderValue = [];
        this.quoteValue = '';
      }
    },
    filterGroup(val) {
      this.conditionList = val;
    },
    // 引用字段
    getRuleField() {
      ruleField().then(res => {
        this.fieldList = res.data;
      }).catch(err => {
        console.error(err);
      });
    },
    filedSelect(item) {
      this.quoteField = this.fieldList.find(i => i.value === item[0]);
    },
    quoteFun(item, clear) {
      const value = item.label;
      if (!value || value === '') return;
      this.formulaList.push(item);
      if (clear === 'cascaderValue') {
        this.cascaderValue = '';
        this.quoteField = '';
      } else if (clear === 'quoteValue') {
        this.quoteValue = '';
      }
    },
    keyupEvent(value) {
      const str = numerical(value);
      this.quoteValue = str;
    },
    deleteFormula(index) {
      this.formulaList.splice(index, 1);
    },
    toSave(params) {
      ruleAdd(params).then(res => {
        this.$message.success('提交成功');
        this.$emit('ruleClose', false, this.resourceGroupId);
      }).catch(err => {
        console.error(err);
        this.$emit('ruleClose', false);
      });
    },
    toEdit(id, params) {
      ruleEdit(id, params).then(res => {
        this.$message.success('修改成功');
        this.$emit('ruleClose', false, this.resourceGroupId);
      }).catch(err => {
        console.error(err);
        this.$emit('ruleClose', false);
      });
    },
    toSumbit() {
      this.closeDialog = !this.closeDialog; // 标记弹窗的关闭打开
      this.conditionList.map(item => {
        if (item.conditions.key === '下单形式') {
          item.conditions.value = item.conditions.value && item.conditions.value.length ? JSON.stringify(item.conditions.value) : null;
        }
        return item;
      });
      let calculationFormula = '';
      this.formulaList.map(item => {
        calculationFormula += item.label + ' ';
      });
      const params = {
        calculationFormula,
        conditionArr: this.conditionList,
        resourceId: this.resourceGroupId,
        formulaList: this.formulaList
      };
      if (!this.ruleId) {
        this.toSave(params);
      } else {
        this.toEdit(this.ruleId, params);
      }
      this.conditionList = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.rule-dialog {
  &::v-deep {
    .el-dialog__body {
      padding: 24px 24px 0 24px !important;
      max-height: 700px;
      overflow: auto;
    }
  }
  .filter-form {
    margin-top: 25px;
    .title {
      font-size: 14px;
      line-height: 1;
      font-weight: 500;
      font-family: PingFangSC-Medium,PingFang SC;
      color: #333;
      margin-bottom: 16px;
    }
    .formula-option {
      width:240px;
      height:32px;
      border-radius:4px;
      border:1px solid rgba(221,221,221,1);
      cursor: pointer;
      display: flex;
      overflow: hidden;
      align-items: center;
    }
    .formula-option-tag {
      padding: 0 8px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
      margin: 0 4px;
      white-space: nowrap;
    }
    .quote-tag {
      width:24px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
    }
    .back-btn {
      width: 80px;
      height: 32px;
      font-size: 14px;
      color: #406EFF;
      padding: 7px;
    }
  }
}
.global-mobile-dialog {
  ::v-deep .el-form-item {
    .el-form-item__content {
      display: flex;
      .quote-btn {
        margin-left: 8px;
      }
    }
  }
}
</style>
<style lang="scss">
.rule-tooltip-formula {
  padding: 5px 2px;
  max-width: 240px;
  border: 1px solid #ddd !important;
  .tooltip-formula-content {
    display: flex;
    flex-wrap: wrap;
    .formula-option-tag {
      padding: 0 8px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 4px;
      cursor: pointer;
      font-size: 12px;
      margin: 0 4px;
      white-space: nowrap;
    }
  }
  .popper__arrow {
    border-top-color: #ddd !important;
  }
}
</style>
